import { useState, useEffect } from 'react';
import { Modal, Button, Form, Input, InputNumber, Select } from 'antd';
import Upload from "../upload";
import { getCategory } from "@/api";
import dialogStyle from "./index.module.css";
const { Option } = Select;


function Dialog(props) {
    let { isModalVisible, handleCancel, handleSuccess } = props;
    console.log(isModalVisible);
    // 确定按钮触发，收集表单
    function onFinish(values) {
        handleSuccess(values);
    }

    // 选择框受控
    let [category, setCategory] = useState([]);
    function handleChange(e) {
        setCategory(e)
    }



    let [leimu, setLeimu] = useState([]);
    useEffect(function () {
        if (isModalVisible) {
            getCategory().then(res => {
                setLeimu(res.data.data);
            })
        }
    })


    const validateMessages = {
        required: '${label}是必填的!',
        types: {
            number: '${label}不是一个正确的数字!'
        },
        number: {
            range: '${label} 必须在 ${min} 到 ${max} 之间',
        },
    };

    return (
        <Modal title="添加商品信息" visible={isModalVisible} footer={null} onCancel={handleCancel}>
            <Form name="nest-messages" onFinish={onFinish} validateMessages={validateMessages}>
                <Form.Item name={['imageUrl']} label="上传样图">
                    <Upload></Upload>
                </Form.Item>

                <Form.Item name={['category_id']} label="商品类目" rules={[{ required: true }]} >
                    <Select value={category} style={{ width: 120 }} onChange={handleChange} >
                        {leimu.map(item => {
                            return <Option value={item.category_id} key={item._id}>{item.categoryName}</Option>
                        })}
                    </Select>
                </Form.Item>

                <Form.Item name={['productName']} label="商品名称" rules={[{ required: true }]}>
                    <Input />
                </Form.Item>

                <Form.Item name={['price']} label="商品价格"
                    rules={[{ type: 'number', min: 0.1, max: 99999, required: true }]} >
                    <InputNumber />
                </Form.Item>

                <Form.Item name={['description']} rules={[{ required: true }]} label="商品描述" >
                    <Input.TextArea />
                </Form.Item>

                <Form.Item name={['inventory']} label="商品库存" rules={[{ required: true }]}>
                    <Input />
                </Form.Item>

                <Form.Item className={dialogStyle.optionBtn}>
                    <Button type="primary" htmlType="submit">确定</Button>
                    <Button type="danger" onClick={handleCancel}>取消</Button>
                </Form.Item>
            </Form>
        </Modal>
    )
}

export default Dialog;